#include "mainwindow.h"
#include "ui_mainwindow.h"



#define RX_Value_Len 12
float   RX_Value[RX_Value_Len] = {0};


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    /*菜单栏*/
    connect(ui->actionAuthor,&QAction::triggered,
            [=](){
                QMessageBox::about(this,"About","作者：李涛 \nInfo：2020级电科学硕 \n指导老师：殷兴辉教授 \n单位：河海大学计信院 ");
    });
    connect(ui->actionVersion,&QAction::triggered,
            [=](){
                QMessageBox::about(this,"About","V3.1.0   \n测试版本");
    });

    Serial_RX_BUF_MX = 64;
    //按键初始化
    this->MyPushButtonInit();

    serial = new QSerialPort(this);

    //定时器初始化并且更新日期
    m_timer = new QTimer(this);
    connect(m_timer,&QTimer::timeout,this,&MainWindow::DateAndTimeUpdate);
    m_timer->start(1000);

    /*画图初始化*/
    dynamic_chart = new MyChart;
    static_chart = new MyChart;
    dynamic_chart->setTitle("Dynamic spline chart");
    static_chart->setTitle("static spline chart");


    dynamic_cview = new MyChartView(dynamic_chart);
    static_cview = new MyChartView(static_chart);
    dynamic_cview->setWindowTitle("动态图");
    static_cview->setWindowTitle("静态图");
    dynamic_cview->setRenderHint(QPainter::Antialiasing);
    static_cview->setRenderHint(QPainter::Antialiasing);
    static_cview->setChartStyle(QChart::SeriesAnimations);
    dynamic_cview->resize(1800,600);
    static_cview->resize(1800,600);

    /*子线程初始化*/
    db_T = new SubThread1;
    thread_1 = new QThread(this);
    db_T->moveToThread(thread_1);
    connect(this,&MainWindow::PutDataIntoDB,
            db_T,&SubThread1::SubThread1_Run);

    /*参数默认值*/
    this->Tass = 150;
    this->DeltaK = 2;
    ui->progressBar->setMaximum((int)(this->Tass*this->DeltaK*100));
    ui->progressBar->setValue(0);

    //日期字符串
    dateStr = QDate::currentDate().toString("yyyy-MM-dd");

}

MainWindow::~MainWindow()
{
    delete ui;
    delete dynamic_chart;
    delete static_chart;
    delete dynamic_cview;
    delete static_cview;
    delete myParaWidget;
    delete dbView;
}


void MainWindow::DataBaseInit(void)
{

    //数据库操作 -->加括号是为了 删除连接前 释放db和query
    {
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE","Mainconnect");
    db.setDatabaseName("./tssDB.db");
    db.setPassword("4414");
    if(!db.open()){
        qDebug() << "Fail to open DB";
      return;
    }else{
        qDebug() << "succeed to open DB";
    }
    QSqlQuery query(db);

    //判断该数据表格是否存在
    query.exec(QString("select count(*) from sqlite_master where type='table' and name='%1';").arg(dateStr));
    if(query.next()){
        if(query.value(0).toInt()==0){//该表不存在-->创建一个该表
            query.exec(QString("create table \"%1\"(Time text primary key not null,Vms real,Tms real);").arg(dateStr));
        }else{
            //该表已经存在
        }
    }

    //判断 参数表中是否有该日的数据--没有则插入该日的日期--后续只需要更新参数信息
    query.exec(QString("select Date from Para where Date = '%1';").arg(dateStr));
    if(query.next()){
        //qDebug() << "有数据";
        //qDebug() << query.value("Date").toString();
    }else{
        //qDebug() <<"没有数据";
         query.exec(QString("insert into Para(Date) values('%1');").arg(dateStr));
    }
    //关闭数据库
    db.close();
    }
    QSqlDatabase::removeDatabase("Mainconnect");
}


void MainWindow::PutParaIntoDataBase(void)
{
    {
        QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE","Mainconnect");
        db.setDatabaseName("./tssDB.db");
        db.setPassword("4414");
        if(!db.open()){
            qDebug() << "Fail to open DB";
          return;
        }else{
            qDebug() << "succeed to open DB";
        }
        QSqlQuery query(db);

        //数据更新
        //Tg Vg数据更新
        query.exec(QString("UPDATE Para SET Tg = %1, Vg = %2  WHERE Date = '%3';").arg(QString::number(this->Tg,'f',3)).arg(QString::number(this->Vg,'f',3)).arg(dateStr));
        //Vss Tass数据更新
        query.exec(QString("UPDATE Para SET Vss = %1, Tass = %2  WHERE Date = '%3';").arg(QString::number(this->Vss,'f',3)).arg(QString::number(this->Tass,'f',3)).arg(dateStr));
        //关闭数据库
        db.close();
    }
    QSqlDatabase::removeDatabase("Mainconnect");

}




void MainWindow::SysConfigAfterConnected()
{
    //数据库初始化
    this->DataBaseInit();
    //启动线程 但是没有启动线程处理函数-->放到连接之后的功能中去
    thread_1->start();
    //只能通过 signal -slot 方式调用启动线程处理函数
    //emit this->StartProcessSerialRxData(xxxx,xxx);
}

void MainWindow::DateAndTimeUpdate()
{
    static int i =0;
    /* 时间显示 ：再来个定时器更新*/
    ui->lineEdit_time->setText(QTime::currentTime().toString("hh:mm:ss"));

    if(i%3600 == 0){ //每小时 更新一次时间
        QDate d = QDate::currentDate();
        ui->lineEdit_date->setText(d.toString("yyyy-MM-dd ddd"));
        i = 1;
    }
    i++;

    /*将buf中的数据数据写全部入*/


    /*test 自动生成点试试*/
/*
    quint8 test_buf[12];
    *((float*)(test_buf+1)) = QRandomGenerator::global()->bounded(800)+2500;
    qDebug() <<  *((float*)(test_buf+1));
    *((float*)(test_buf+5)) = QRandomGenerator::global()->bounded(500)+1200;
    qDebug() <<  *((float*)(test_buf+5));
    test_buf[9] = t.hour();
    test_buf[10] = t.minute();
    test_buf[11] = t.second();
    this->DrawPoint(test_buf);
    qDebug() << test_buf[9] << ":" << test_buf[10] << ":" <<  test_buf[11];
*/

}



void MainWindow::MyPushButtonInit()
{
    /*初始化按钮*/
    //串口相关
    ui->pushButton_openSerial->setEnabled(false);
    ui->pushButton_closeSerial->setEnabled(false);
    //指令操作界面
    ui->pushButton_show_hide_sysPara->setEnabled(false);
    ui->pushButton_clearLocationInfoinRom->setEnabled(false);
    ui->pushButton_antebbaPosition->setEnabled(false);
    ui->pushButton_antennaInit->setEnabled(false);
    ui->pushButton_locationGet->setEnabled(false);
    ui->pushButton_locationCalibration->setEnabled(false);
    ui->pushButton_timeGet->setEnabled(false);
    ui->pushButton_timeCalibration->setEnabled(false);
    ui->pushButton_startTrack->setEnabled(false);
    ui->pushButton_stopTrack->setEnabled(false);
    ui->pushButton_toTargetSet->setEnabled(false);
    ui->pushButton_sysStatusGet->setEnabled(false);
    /*参数类*/
    ui->pushButton_sysParaGet->setEnabled(false);
    ui->pushButton_getScalerPara->setEnabled(false);
    ui->pushButton_trackPara->setEnabled(false);
    ui->pushButton_getAWFA_Para->setEnabled(false);
    ui->pushButton_ELcAZc->setEnabled(false);
    ui->pushButton_Tass->setEnabled(false);
    //数据库界面
    ui->pushButton_showData->setEnabled(false);
    ui->pushButton_putParaIntoDB->setEnabled(false);
    ui->pushButton_readDataFromDowner->setEnabled(false);
    ui->pushButton_clearDownerData->setEnabled(false);
    //图形界面
    ui->pushButton_shDynaicChart->setEnabled(false);
    ui->pushButton_shStaticChart->setEnabled(false);
   //最下面发送
    ui->pushButton_sendTextEditData->setEnabled(false);
}



void MainWindow::on_pushButton_openSerial_clicked()
{
    //端口号选择
    QString portName = QString(ui->comboBox_serialPort->currentText()).section("--",0,0);
    if(portName == ""){
        ui->statusbar->showMessage("串口打开失败：没有找到串口",1000);
       return;
    }
    serial->setPortName(QString(ui->comboBox_serialPort->currentText()).section("--",0,0));

    //波特率选择
    if(ui->comboBox_baudRate->currentIndex() == 0){

        serial->setBaudRate(QSerialPort::Baud115200);
    }else if(ui->comboBox_baudRate->currentIndex() == 1){
        serial->setBaudRate(QSerialPort::Baud9600);
    }else{ //其他的需要的时候再添加吧
        ui->statusbar->showMessage("串口打开失败：错误的波特率选择",1000);
        return;
    }

    //数据位
    if(ui->comboBox_dataBits->currentIndex() == 0){
        serial->setDataBits(QSerialPort::Data8);
    }else if(ui->comboBox_dataBits->currentIndex() == 1){
        serial->setDataBits(QSerialPort::Data7);
    }else if(ui->comboBox_dataBits->currentIndex() == 2){ //其他的需要的时候再添加吧
        serial->setDataBits(QSerialPort::Data6);
    }else{
        ui->statusbar->showMessage("串口打开失败：错误的数据选择",1000);
        return;
    }

    //停止位
    if(ui->comboBox_stopbits->currentIndex() == 0){
        serial->setStopBits(QSerialPort::OneStop); /*一个停止位*/
    }else if(ui->comboBox_stopbits->currentIndex() == 1){
        serial->setStopBits(QSerialPort::TwoStop); /*两个停止位*/
    }else{
        ui->statusbar->showMessage("串口打开失败：错误的数据选择",1000);
        return;
    }

    //校验位
    if(ui->comboBox_parity->currentIndex() == 0){
        serial->setParity(QSerialPort::NoParity); /*无校验位*/
    }else if(ui->comboBox_parity->currentIndex() == 1){
        serial->setParity(QSerialPort::EvenParity);
    }else if(ui->comboBox_parity->currentIndex() == 2){
        serial->setParity(QSerialPort::OddParity);
    }else{
        ui->statusbar->showMessage("串口打开失败：错误的数据选择",1000);
        return;
    }

    //串口打开
    bool  isOpen = serial->open(QIODevice::ReadWrite); //这玩意注意一下 帮助文档是 6  该版本是5
    if(isOpen == true){
        connect(serial,&QIODevice::readyRead,this,&MainWindow::SerialDataReadAndProcess);
        connect(serial,&QSerialPort::errorOccurred,this,&MainWindow::SerialErrorHandle);
        ui->statusbar->showMessage("串口打开成功",800);

        ui->pushButton_openSerial->setEnabled(false);
        ui->pushButton_timeGet->setEnabled(true);
        ui->pushButton_timeCalibration->setEnabled(true);
        ui->pushButton_closeSerial->setEnabled(true);
        ui->pushButton_locationGet->setEnabled(true);
        ui->pushButton_locationCalibration->setEnabled(true);
        ui->pushButton_show_hide_sysPara->setEnabled(true);
        ui->pushButton_clearLocationInfoinRom->setEnabled(true);
        ui->pushButton_antebbaPosition->setEnabled(true);
        ui->pushButton_antennaInit->setEnabled(true);
        ui->pushButton_startTrack->setEnabled(true);
        ui->pushButton_stopTrack->setEnabled(true);
        ui->pushButton_toTargetSet->setEnabled(true);
        ui->pushButton_sysStatusGet->setEnabled(true);
        ui->pushButton_showData->setEnabled(true);
        ui->pushButton_putParaIntoDB->setEnabled(true);
        ui->pushButton_readDataFromDowner->setEnabled(true);
        ui->pushButton_clearDownerData->setEnabled(true);
        ui->pushButton_sendTextEditData->setEnabled(true);
        ui->pushButton_Tass->setEnabled(true);
        ui->pushButton_shDynaicChart->setEnabled(true);
        ui->pushButton_shStaticChart->setEnabled(true);
        ui->label_sysStatusLed->setStyleSheet("min-width: 26px; min-height: 26px;max-width:26px; max-height: 26px;border-radius: 13px;  border:1px solid black;background:green"); //设置状态
    }else{
        ui->statusbar->showMessage("串口打开失败",1000);
        return;
    }
    this->SysConfigAfterConnected();
}

void MainWindow::SerialErrorHandle(QSerialPort::SerialPortError error)
{
    if(error == QSerialPort::ResourceError){
        serial->clear();
        serial->disconnect(this); //断开连接
        serial->close();
        ui->statusbar->showMessage("串口资源出错",1000);
        this->MyPushButtonInit();
    }
}

void MainWindow::SerialDataReadAndProcess()
{
    ui->statusbar->showMessage("收到信息",500);
    quint8 buf[Serial_RX_BUF_MX];
    quint8 len = this->serial->read((char *)buf,Serial_RX_BUF_MX);
    if( len > 0){
        if(buf[0] == 0x55 && buf[1] == len && buf[len-1] == 0xDD){ //接收到单片机的包 三次比对都对的上
            this->SerialPortRxDataProcess((buf+2),len-3); //掐两个头去一个尾传输给解析函数
        }else{
            //并非指令 直接打印出来
            ui->textEdit->append(QString((char *)buf));
        }
    }else{
        //没有接收到数据 buf清零
        memset(buf,0,len);
    }
}

/*串口刷新*/
void MainWindow::on_pushButton_serialScan_clicked()
{
    /**/
    ui->comboBox_serialPort->clear();
    foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts()){
        ui->comboBox_serialPort->addItem(QString("%1--%2").arg(info.portName(),info.description()));
    }
    if(ui->comboBox_serialPort->count() > 0){
        ui->pushButton_openSerial->setEnabled(true);
    }
}



/*数据处理函数*/
quint8 MainWindow::SerialPortRxDataProcess(quint8 *buf,quint8 len)
{


    if(buf[0] > 0x7F && len > 5){
         switch(buf[0]){
             case 0x80: //核心信息
                /*描点函数*/
             this->DrawPoint(buf);
             break;

             case 0x84://跟踪任务的角度信息
                ui->lineEdit_EL->setText(QString::number(*((float*)(buf+1)),'f',2));
                ui->lineEdit_AZ->setText(QString::number(*((float*)(buf+5)),'f',2));
             break;

             case 0x88://恒温箱
                ui->lineEdit_boxT->setText(QString::number(*((float*)(buf+1)),'f',3));
             break;

             case 0x89://环境温度
                ui->lineEdit_enrT->setText(QString::number(*((float*)(buf+1)),'f',3));
             break;

            default:
             break;
         }
    }else if(buf[0] < 0x80 && buf[0] > 0x6F){
        /* 处理系统初始化后上传的参数 */
        switch(buf[0]){
        case 0x70:
            this->Vg =    *((quint16*)(buf+1))*330/4096.0;
            this->Tg = (float)(*((qint16*)(buf+3)))/100.0 + 273.15;
            this->Vss =  *((quint16*)(buf+5))*330/4096.0;
            this->Tass = *((float*)(buf+19));
            ui->progressBar->setMaximum((int)(this->Tass*100*this->DeltaK));
            this->dynamic_chart->setSunBreakingReferenceLine(this->Tass*this->DeltaK);
            this->static_chart->setSunBreakingReferenceLine(this->Tass*this->DeltaK);
            break;
        case 0x71:
            ui->textEdit->append(QString("ELc:"));
            ui->textEdit->append(QString::number(*((float*)(buf+1)),'f',3));
            ui->textEdit->append(QString("AZc:"));
            ui->textEdit->append(QString::number(*((float*)(buf+5)),'f',3));
            break;
        case 0x72:
            ui->lineEdit_longitude->setText(QString::number(*((float*)(buf+1)),'f',6));
            ui->lineEdit_latitude->setText(QString::number(*((float*)(buf+5)),'f',6));
            this->Tass = *((float*)(buf+9));
            ui->progressBar->setMaximum((int)(this->Tass*100*this->DeltaK));
            /* 图形类设置一条红线 */
            this->dynamic_chart->setSunBreakingReferenceLine(this->Tass*this->DeltaK);
            this->static_chart->setSunBreakingReferenceLine(this->Tass*this->DeltaK);
            //角度设置
            ui->lineEdit_EL->setText(QString::number(*((float*)(buf+13)),'f',2));
            ui->lineEdit_AZ->setText(QString::number(*((float*)(buf+17)),'f',2));
            break;
        case 0x73:
            ui->lineEdit_enrT->setText(QString::number(*((float*)(buf+1)),'f',3));
            ui->lineEdit_boxT->setText(QString::number(*((float*)(buf+5)),'f',3));
            break;
        case 0x77:
            ui->statusbar->showMessage(QString("CMD 0X%1 Completed").arg(buf[0],16),888);
            //指令操作时生成对话框 等待该信号产生
            break;
        default:
            break;
        }

    }else{ // 5位数据
        float tempf;
        switch(buf[0]){
            case 0x67: //status
                tempf  = *((float*)(buf+1));
                ui->lineEdit_sysStatus->setText(QString::number(tempf,'f',3));
                break;

            case 0x50: //日期
                ui->textEdit->append(QString("Date 20%1-%2-%3 ").arg(buf[1],buf[2],buf[3])); //最多3个
                ui->textEdit->append(QString("WeekDay %1").arg(buf[4]));
                break;

            case 0x60:  //时间
                ui->textEdit->append(QString("Time %1:%2:%3 ").arg(buf[1],buf[2],buf[3])); //最多3个
                break;

            case 0x51: //经度
                tempf  = *((float*)(buf+1));
                ui->lineEdit_longitude->setText(QString::number(tempf,'f',6));
                break;

            case 0x61: //纬度
                tempf  = *((float*)(buf+1));
                ui->lineEdit_latitude->setText(QString::number(tempf,'f',6));
            break;

            case 0x59: //Tass
                tempf  = *((float*)(buf+1));
                this->Tass = tempf;
                ui->progressBar->setMaximum((int)(DeltaK*tempf*100));
                /* 图形类设置一条红线 */
                this->dynamic_chart->setSunBreakingReferenceLine(this->Tass*this->DeltaK);
                this->static_chart->setSunBreakingReferenceLine(this->Tass*this->DeltaK);
            break;

            case 0x52: //Vg
                this->Vg = *((float*)(buf+1))*330/4096;
                this->myParaWidget->ShowPara_Vg(this->Vg);
            break;

            case 0x53: //Tg
                this->Tg = *((float*)(buf+1))/100.0 + 273.15;
                this->myParaWidget->ShowPara_Tg(this->Tg);
            break;

            case 0x54:  //Vss
                this->Vss = *((float*)(buf+1))*330/4096;
                this->myParaWidget->ShowPara_Vss(this->Vss);
            break;

            case 0x5A: //AZc
                tempf  = *((float*)(buf+1));
                ui->textEdit->append(QString("AZc:"));
                ui->textEdit->append(QString::number(tempf,'f',3));
            break;

            case 0x6A: //ELc
                tempf  = *((float*)(buf+1));
                ui->textEdit->append(QString("ELc:"));
                ui->textEdit->append(QString::number(tempf,'f',3));
            break;

            //sys_Para
            case 0xF0://Tr
                this->myParaWidget->ShowPara_Tr(*((float*)(buf+1)));
                break;
            case 0xF1://Tz
                this->myParaWidget->ShowPara_Tz(*((float*)(buf+1)));
                break;
            case 0xF2://KPara
                this->myParaWidget->ShowPara_KPara(*((float*)(buf+1)));
                break;
            case 0xF3://DeltaK
                this->DeltaK = *((float*)(buf+1)); //保存到成员变量
                this->myParaWidget->ShowPara_DeltaK(this->DeltaK);
                ui->progressBar->setMaximum((int)(this->DeltaK*this->Tass*100));
                this->dynamic_chart->setSunBreakingReferenceLine(this->Tass*this->DeltaK);
                this->static_chart->setSunBreakingReferenceLine(this->Tass*this->DeltaK);
                break;

            //track
            case 0xF8: // track Period
                this->myParaWidget->ShowPara_trackPeriod(buf[1]);
                break;

            case 0xF9: //trackError_Min
                 tempf  = *((float*)(buf+1));
                 this->myParaWidget->ShowPara_trackError_Min(tempf);
            break;

            case 0xFA: //trackError_Max
                tempf  = *((float*)(buf+1));
                this->myParaWidget->ShowPara_trackError_Max(tempf);
            break;
            //AWFA
            case 0xFC: //AWFA
                tempf  = *((float*)(buf+1));
                this->myParaWidget->ShowPara_AWFA_WD(tempf);
            break;

            case 0xFD: //
                tempf  = *((float*)(buf+1));
                this->myParaWidget->ShowPara_AWFA_WMin(tempf);
            break;

            case 0xFE: //
                tempf  = *((float*)(buf+1));
                this->myParaWidget->ShowPara_AWFA_WMax(tempf);
            break;

            case 0xFF: //
                tempf  = *((float*)(buf+1));
                this->myParaWidget->ShowPara_AWFA_WAC(tempf);
            break;

        default:
            break;
        }
    }

    return 0;
}


void MainWindow::DrawPoint(quint8* buf)
{
    float Vms,Tms;
    Vms = (*((float*)(buf+1))/4096.0f)*330;
    Tms = *((float*)(buf+5));
    QTime pointTime = QTime(buf[9],buf[10],buf[11]);
    ui->lineEdit_outValue->setText(QString::number(Vms,'f',3));
    ui->lineEdit_T->setText(QString::number(Tms,'f',3));

    //数据传入子线程
    emit PutDataIntoDB(pointTime,Vms,Tms);

    if((int)Tms*100 >= ui->progressBar->maximum()){ //爆发：红色
        ui->progressBar->setValue(ui->progressBar->maximum());
        ui->label_sunBreakLed->setStyleSheet("min-width: 26px; min-height: 26px;max-width:26px; max-height: 26px;border-radius: 13px;  border:1px solid black;background:red"); //设置红色
    }else if((int)(Tms*125) >= ui->progressBar->maximum()){ // >= 80% 黄色
        ui->label_sunBreakLed->setStyleSheet("min-width: 26px; min-height: 26px;max-width:26px; max-height: 26px;border-radius: 13px;  border:1px solid black;background:yellow"); //设置红色
        ui->progressBar->setValue((int)(Tms*100));
    }else{ //绿色
        ui->label_sunBreakLed->setStyleSheet("min-width: 26px; min-height: 26px;max-width:26px; max-height: 26px;border-radius: 13px;  border:1px solid black;background:green"); //设置红色
        ui->progressBar->setValue((int)(Tms*100));
    }

    if(static_chart->isExistPoint()){//第一个点？
        dynamic_chart->startDateTime.setTime(pointTime);
        dynamic_chart->endDateTime =
                dynamic_chart->startDateTime.addSecs(60*12); //设置12分钟的间隔
        dynamic_chart->setAxisXRange();
        dynamic_chart->ScrollParaInit();

        static_chart->startDateTime.setTime(pointTime);
        static_chart->endDateTime =
                static_chart->startDateTime.addSecs(3600*2);
        static_chart->setAxisXRange();

        dynamic_chart->setDateTime = dynamic_chart->startDateTime;
        dynamic_chart->DrawNewPointwithScrollOneTick(Tms);
        static_chart->setDateTime = static_chart->startDateTime;
        static_chart->DrawNewPoint(Tms);
        //static_chart->DrawNewPointwithSetMaxRange(Tms);
        this->dynamic_chart->setSunBreakingReferenceLine(this->Tass*this->DeltaK);
        this->static_chart->setSunBreakingReferenceLine(this->Tass*this->DeltaK);
    }else{
        dynamic_chart->setDateTime.setTime(pointTime);
        dynamic_chart->DrawNewPointwithScrollOneTick(Tms);
        static_chart->setDateTime.setTime(pointTime);
        static_chart->DrawNewPoint(Tms);
        if(buf[9] > (static_chart->endDateTime.time().hour() - 2)){ //给予多1个小时的范围
            static_chart->MaxIncreaseOneTick(); //加一个小时的最大值
        }
    }
}



void MainWindow::on_pushButton_closeSerial_clicked()
{
    serial->clear();
    serial->disconnect(this); //断开连接
    serial->close();
    ui->statusbar->showMessage("串口关闭",1000);
    this->MyPushButtonInit();
    ui->label_sysStatusLed->setStyleSheet("min-width: 26px; min-height: 26px;max-width:26px; max-height: 26px;border-radius: 13px;  border:1px solid black;background:red"); //设置状态
}



void MainWindow::on_pushButton_timeCalibration_clicked()
{
    quint8 buf[11] = {0};
    QTime t = QTime::currentTime();
    QDate d = QDate::currentDate();

    //帧头
    buf[0] = 0xAA;
    buf[1] = 0x0B; //11
    buf[2] = 0xA0;

    //年月日 星期期
    buf[3] = (quint8)(d.year() - 2000);
    buf[4] = (quint8)d.month();
    buf[5] = (quint8)d.day();
    buf[6] = (quint8)d.dayOfWeek();

    // 时间
    buf[7] =  t.hour();
    buf[8] =  t.minute();
    buf[9] =  t.second();

    //结束帧
    buf[10] = 0xCC;

    //串口发送！
    this->serial->write((const char*)buf,11);
    ui->statusbar->showMessage("时间校准指令发送完成",800);
}




void MainWindow::on_pushButton_locationCalibration_clicked()
{


    /*对话框获取经纬度数据*/
    bool ok1,ok2;

    qreal longtitude = QInputDialog::getDouble(this,"经纬度校准输入框","请输入经度(6位有效数字)",120.782514,-180,180,6,&ok1);
    qreal latitude = QInputDialog::getDouble(this,"经纬度校准输入框","请输入纬度(6位有效数字)",35.914785,-180,180,6,&ok2);
    if(!(ok1&&ok2)){
        ui->statusbar->showMessage("经纬度信息输入有误",1000);
        return;
    }

    quint8 buf[12] = {0};
    //帧头
    buf[0] = 0xAA;
    buf[1] = 0x0C; //12
    buf[2] = 0xA1;

    *((float*)(buf+3)) = (float)longtitude;
    *((float*)(buf+7)) = (float)latitude;

    buf[11] = 0xCC;

    //串口发送！
    this->serial->write((const char*)buf,12);
    ui->statusbar->showMessage("经纬度校准指令发送完成",800);
}


void MainWindow::on_pushButton_textEditClear_clicked()
{
    ui->textEdit->clear();
}


void MainWindow::on_pushButton_shDynaicChart_clicked()
{
    static bool flag1 = true;
    if(flag1){
        dynamic_cview->show();
        dynamic_chart->startDateTime = dynamic_chart->setDateTime;
        dynamic_chart->endDateTime = dynamic_chart->startDateTime.addSecs(60*12);
        dynamic_chart->setAxisXRange();
        dynamic_chart->ScrollParaInit();
        flag1 = false;
    }else{
        dynamic_cview->hide();
        flag1 = true;
    }
}


void MainWindow::on_pushButton_shStaticChart_clicked()
{
    static bool flag2 = true;
    if(flag2){
        static_cview->show();
        flag2 = false;
    }else{
        static_cview->hide();
        flag2 = true;
    }
}

/*获取下位机的时间信息*/
void MainWindow::on_pushButton_timeGet_clicked()
{
    quint8 buf[4] = {0xAA,0x04,0xB0,0xCC};
    //串口发送！
    this->serial->write((const char*)buf,4);
}

/**/


void MainWindow::on_pushButton_locationGet_clicked()
{
    quint8 buf[4] = {0xAA,0x04,0xB1,0xCC};
    //串口发送！
    this->serial->write((const char*)buf,4);
}


void MainWindow::on_pushButton_sysParaGet_clicked()
{
    quint8 buf[4] = {0xAA,0x04,0xC0,0xCC};
    //串口发送！
    this->serial->write((const char*)buf,4);
}


void MainWindow::on_pushButton_getScalerPara_clicked()
{
    //0xAA-0x04-0xC1-0xCC
    quint8 buf[4] = {0xAA,0x04,0xC1,0xCC};
    //串口发送！
    this->serial->write((const char*)buf,4);

}


void MainWindow::on_pushButton_show_hide_sysPara_clicked()
{
    static bool flag3 = true;
    if(flag3){
        /*参数窗口空间分配*/
        myParaWidget = new ParaWidget;
        myParaWidget->show();
        //使能按钮
        ui->pushButton_getScalerPara->setEnabled(true);
        ui->pushButton_sysParaGet->setEnabled(true);
        ui->pushButton_getAWFA_Para->setEnabled(true);
        ui->pushButton_trackPara->setEnabled(true);
        ui->pushButton_ELcAZc->setEnabled(true);

        connect(myParaWidget,&ParaWidget::TrReset,this,&MainWindow::SetTrPara);
        connect(myParaWidget,&ParaWidget::TzReset,this,&MainWindow::SetTzPara);
        connect(myParaWidget,&ParaWidget::DeltaKReset,this,&MainWindow::SetDeltaKPara);
        connect(myParaWidget,&ParaWidget::KParaReset,this,&MainWindow::SetKParaPara);
        connect(myParaWidget,&ParaWidget::TrackParaReset,this,&MainWindow::SetTrackPara);
        connect(myParaWidget,&ParaWidget::AWFAParaReset,this,&MainWindow::SetAWFAPara);
        flag3 = false;
    }else{
        myParaWidget->hide();
        myParaWidget->disconnect(this); //断开连接
        //失能按钮
        ui->pushButton_sysParaGet->setEnabled(false);
        ui->pushButton_getScalerPara->setEnabled(false);
        ui->pushButton_trackPara->setEnabled(false);
        ui->pushButton_getAWFA_Para->setEnabled(false);
        ui->pushButton_ELcAZc->setEnabled(false);
        flag3 = true;
        delete myParaWidget; //空间回收
    }

}

void MainWindow::SetTrackPara(quint8 whichPara,float Value)
{
    quint8 buf[5] = {0};

    if(whichPara == 1){
        buf[0] = 0xF8;
        buf[1] = (quint8)Value;
    }else if(whichPara == 2){
        buf[0] = 0xF9;
        *((float*)(buf+1)) = Value;
    }else if(whichPara == 3){
        buf[0] = 0xFA;
        *((float*)(buf+1)) = Value;
    }
    SerialTxPocket(buf,5);

}

void MainWindow::SetAWFAPara(quint8 whichPara,float Value)
{
    quint8 buf[5] = {0};
    if(whichPara == 1){
        buf[0] = 0xFC;
        *((float*)(buf+1)) = Value;
    }else if(whichPara == 2){
        buf[0] = 0xFD;
        *((float*)(buf+1)) = Value;
    }else if(whichPara == 3){
        buf[0] = 0xFE;
        *((float*)(buf+1)) = Value;
    }else if(whichPara == 4){
        buf[0] = 0xFF;
        *((float*)(buf+1)) = Value;
    }
        SerialTxPocket(buf,5);
}

/*清除下位机内存中保存的 经纬度信息 0xAA-0x04-0xD1-0xCC*/
void MainWindow::on_pushButton_clearLocationInfoinRom_clicked()
{
    quint8 buf[4] = {0xAA,0x04,0xC4,0xCC};
    //串口发送！
    this->serial->write((const char*)buf,4);
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    int ret = QMessageBox::question(this,"确认","是否需要关闭本程序");
    if(ret == QMessageBox::Yes){
        //关闭串口
        //处理关闭窗口事件
        thread_1->wait();
        thread_1->quit();
        event->accept();
    }else{
        //不关闭
        event->ignore(); //事件继续传递给父组件
    }
}

/**/
void MainWindow::SerialTxPocket(unsigned char * buf,uint8_t len)
{
    unsigned char Tx_buf[len+3];

    Tx_buf[0] = 0xAA;
    Tx_buf[1] = len+3;
    memcpy(&Tx_buf[2],buf,len);
    Tx_buf[len+2] = 0xCC;

    this->serial->write((const char*)Tx_buf,len+3);
}


/**/
void MainWindow::SetTrPara(float value)
{
   //qDebug() << value;
    quint8 buf[8] = {0};
    buf[0] = 0xAA;
    buf[1] = 0x08;
    buf[2] = 0xF0;
    *((float*)(buf+3)) = value;
    buf[7] = 0xCC;

    //串口发送！
    this->serial->write((const char*)buf,8);
}

void MainWindow::SetTzPara(float value)
{
    //qDebug() << value;
    quint8 buf[8] = {0};
    buf[0] = 0xAA;
    buf[1] = 0x08;
    buf[2] = 0xF1;
    *((float*)(buf+3)) = value;
    buf[7] = 0xCC;

    //串口发送！
    this->serial->write((const char*)buf,8);
}
void MainWindow::SetDeltaKPara(float value)
{
    //qDebug() << value;
    quint8 buf[8] = {0};
    buf[0] = 0xAA;
    buf[1] = 0x08;
    buf[2] = 0xF2;
    *((float*)(buf+3)) = value;
    buf[7] = 0xCC;

    //串口发送！
    this->serial->write((const char*)buf,8);
}
void MainWindow::SetKParaPara(float value)
{
    //qDebug() << value;
    quint8 buf[8] = {0};
    buf[0] = 0xAA;
    buf[1] = 0x08;
    buf[2] = 0xF3;
    *((float*)(buf+3)) = value;
    buf[7] = 0xCC;

    //串口发送！
    this->serial->write((const char*)buf,8);
}

void MainWindow::on_pushButton_ELcAZc_clicked()
{
    quint8 cmd = 0xC2;
    this->SerialTxPocket(&cmd,1);
}

void MainWindow::on_pushButton_trackPara_clicked()
{
    quint8 cmd = 0xC4;
    this->SerialTxPocket(&cmd,1);
}

void MainWindow::on_pushButton_getAWFA_Para_clicked()
{
    quint8 cmd = 0xC5;
    this->SerialTxPocket(&cmd,1);
}


void MainWindow::on_pushButton_Tass_clicked()
{
    quint8 cmd = 0xC3;
    this->SerialTxPocket(&cmd,1);
}


void MainWindow::on_pushButton_showData_clicked()
{
    dbView = new database;
    dbView->show();
}


void MainWindow::on_pushButton_putParaIntoDB_clicked()
{
    this->PutParaIntoDataBase();
}


void MainWindow::on_pushButton_antebbaPosition_clicked()
{
    /*输入框--指定角度位移*/
    /*对话框获取经纬度数据*/
    bool ok1,ok2;

    qreal az = QInputDialog::getDouble(this,"AZ输入框","请输入AZ",90.00,20,300,2,&ok1);
    qreal el = QInputDialog::getDouble(this,"EL输入框","请输入EL",45.00,-15,90,2,&ok2);
    if(!(ok1&&ok2)){
        ui->statusbar->showMessage("角度输入有误",1000);
        return;
    }

    quint8 buf[12] = {0};
    //帧头
    buf[0] = 0xAA;
    buf[1] = 0x0C; //12
    buf[2] = 0xA5;

    *((float*)(buf+3)) = (float)az;
    *((float*)(buf+7)) = (float)el;

    buf[11] = 0xCC;

    //串口发送！
    this->serial->write((const char*)buf,12);
    ui->statusbar->showMessage("天线定位指令发送完成",800);

}


void MainWindow::on_pushButton_startTrack_clicked()
{
    bool ok1,ok2;

    qreal az = QInputDialog::getDouble(this,"AZ偏移量输入框","请输入偏移量AZ",-90.00,-90,90,2,&ok1);
    qreal el = QInputDialog::getDouble(this,"EL偏移量输入框","请输入偏移量EL",-45.00,-90,90,2,&ok2);
    if(!(ok1&&ok2)){
        ui->statusbar->showMessage("角度输入有误",1000);
        return;
    }

    quint8 buf[12] = {0};
    //帧头
    buf[0] = 0xAA;
    buf[1] = 0x0C; //12
    buf[2] = 0xA6;

    *((float*)(buf+3)) = (float)az;
    *((float*)(buf+7)) = (float)el;

    buf[11] = 0xCC;

    //串口发送！
    this->serial->write((const char*)buf,12);
    ui->statusbar->showMessage("天线偏移指令发送完成",800);
}


void MainWindow::on_pushButton_stopTrack_clicked()
{
    quint8 buf[4] = {0xAA,0x04,0xA8,0xCC};
    //串口发送！
    this->serial->write((const char*)buf,4);
}


void MainWindow::on_pushButton_toTargetSet_clicked()
{
    bool ok1,ok2;

    qreal az = QInputDialog::getDouble(this,"AZ扫描单位输入框","请输入AZ扫描单位（0.5）",0,0,80,1,&ok1);
    qreal el = QInputDialog::getDouble(this,"EL扫描单位输入框","请输入EL扫描单位（0.5）",0,0,20,1,&ok2);
    if(!(ok1&&ok2)){
        ui->statusbar->showMessage("输入有误",1000);
        return;
    }

    quint8 buf[12] = {0};
    //帧头
    buf[0] = 0xAA;
    buf[1] = 0x0C; //12
    buf[2] = 0xA9;

    *((float*)(buf+3)) = (float)az;
    *((float*)(buf+7)) = (float)el;

    buf[11] = 0xCC;

    //串口发送！
    this->serial->write((const char*)buf,12);
    ui->statusbar->showMessage("天线偏移指令发送完成",800);

}

